package com.zhoug.mpchart.views;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.github.mikephil.charting.interfaces.datasets.IDataSet;
import com.zhoug.mpchart.R;
import com.zhoug.mpchart.charts.IMPChart;
import com.zhoug.mpchart.data.MPLegendEntry;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

/**
 * 自定义图例
 *
 * @Author: zhoug
 * @Date: 2024-02-19
 * @Description:
 */
public class MPLegendViewGroup extends FrameLayout {
    //布局类型
    private static final int LAYOUT_LINE_HORIZONTAL = 0;//水平线性布局
    private static final int LAYOUT_LINE_VERTICAL = 1;//垂直线性布局
    private static final int LAYOUT_GRID = 2;//网格
    private static final int LAYOUT_STAGGERED_GRID_HORIZONTAL = 3;//瀑布流水平
    private static final int LAYOUT_STAGGERED_GRID_VERTICAL = 4;//瀑布流水平垂直
    private static final int LAYOUT_FLOW = 5;//流式

    /**
     * 布局类型
     */
    private int mLayoutType = LAYOUT_LINE_HORIZONTAL;
    /**
     * 网格布局时每行数据个数
     */
    private int mGridSpanCount = 3;
    private int mMaxLines = -1;//每个单独的图例最少支持换行
    /**
     * 水平间距,
     */
    private int mHorizontalSpace;
    /**
     * 垂直间距
     */
    private int mVerticalSpace;
    //是否支持点击图例隐藏绘制图表
    private boolean mSupportHideDataSet = true;
    //隐藏绘制图表时的图例文字颜色
    private int mHideTextColor = Color.parseColor("#cccccc");
    private int mIconSize;//图例大小
    private int mTextColor;//文字颜色
    private float mTextSize;//文字大小

    private LegendAdapter mLegendAdapter;
    private MPFlowViewGroup mFlowViewGroup;

    private List<MPLegendEntry> mData = new ArrayList<>();
    private IMPChart mChart;

    public MPLegendViewGroup(@NonNull Context context) {
        this(context, null);
    }

    public MPLegendViewGroup(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MPLegendViewGroup(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);
    }

    private void init(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MPLegendViewGroup, defStyleAttr, 0);
        mLayoutType = a.getInt(R.styleable.MPLegendViewGroup_mp_layoutType, LAYOUT_LINE_HORIZONTAL);
        mGridSpanCount = a.getInt(R.styleable.MPLegendViewGroup_mp_gridSpanCount, 3);
        mMaxLines = a.getInt(R.styleable.MPLegendViewGroup_android_maxLines, -1);
        mHorizontalSpace = a.getDimensionPixelOffset(R.styleable.MPLegendViewGroup_mp_horizontalSpace, 0);
        mVerticalSpace = a.getDimensionPixelOffset(R.styleable.MPLegendViewGroup_mp_verticalSpace, 0);
        mIconSize = a.getDimensionPixelOffset(R.styleable.MPLegendViewGroup_mp_icon_size, context.getResources().getDimensionPixelOffset(R.dimen.mp_legend_icon_size));
        mTextColor = a.getColor(R.styleable.MPLegendViewGroup_android_textColor, ContextCompat.getColor(context,R.color.mp_legendTextColor));
        mTextSize = a.getDimension(R.styleable.MPLegendViewGroup_android_textSize, context.getResources().getDimension(R.dimen.mp_legend_text_size));


        a.recycle();

        if (mLayoutType == LAYOUT_FLOW) {
            mFlowViewGroup = new MPFlowViewGroup(getContext());
            LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
            mFlowViewGroup.setLayoutParams(layoutParams);
            addView(mFlowViewGroup);
        } else {
            RecyclerView recyclerView = new RecyclerView(getContext());
            recyclerView.setId(View.generateViewId());
            LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
            recyclerView.setLayoutParams(layoutParams);
            addView(recyclerView);
            mLegendAdapter = new LegendAdapter();
            recyclerView.setAdapter(mLegendAdapter);
            if (mLayoutType == LAYOUT_LINE_VERTICAL) {
                recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, false));
            } else if (mLayoutType == LAYOUT_LINE_HORIZONTAL) {
                recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.HORIZONTAL, false));
            } else if (mLayoutType == LAYOUT_GRID) {
                recyclerView.setLayoutManager(new GridLayoutManager(getContext(), mGridSpanCount));
            } else if (mLayoutType == LAYOUT_STAGGERED_GRID_HORIZONTAL) {
                recyclerView.setLayoutManager(new StaggeredGridLayoutManager(mGridSpanCount, RecyclerView.HORIZONTAL));
            } else if (mLayoutType == LAYOUT_STAGGERED_GRID_VERTICAL) {
                recyclerView.setLayoutManager(new StaggeredGridLayoutManager(mGridSpanCount, RecyclerView.VERTICAL));
            }
        }
    }

    public void setChart(IMPChart chart) {
        this.mChart = chart;
    }

    /**
     * 设置图例数据
     *
     * @param data
     */
    public void setData(List<MPLegendEntry> data) {
        setData(data, false);
    }

    /**
     * 设置图例数据
     *
     * @param data
     * @param notify 是否刷新
     */
    public void setData(List<MPLegendEntry> data, boolean notify) {
        this.mData = data;
        if (notify) {
            notifyDataSetChanged();
        }
    }

    /**
     * 获取对应位置的图例数据
     *
     * @param position
     * @return
     */
    public MPLegendEntry getItemData(int position) {
        if (mData != null && position >= 0 && position < mData.size()) {
            return mData.get(position);
        }
        return null;
    }

    /**
     * 刷新数据
     */
    public void notifyDataSetChanged() {
        if (mLegendAdapter != null) {
            mLegendAdapter.notifyDataSetChanged();
        } else if (mFlowViewGroup != null) {
            mFlowViewGroup.removeAllViews();
            if (mData != null && mData.size() > 0) {
                for (int i = 0; i < mData.size(); i++) {
                    ViewHolder viewHolder = _onCreateViewHolder(mFlowViewGroup);
                    _onBindViewHolder(viewHolder, i);
                    mFlowViewGroup.addView(viewHolder.itemView);
                }
            }

        }
    }

    /**
     * 创建图例布局ViewHolder
     *
     * @param parent
     * @return
     */
    protected ViewHolder _onCreateViewHolder(@NonNull ViewGroup parent) {
        View root = LayoutInflater.from(getContext()).inflate(R.layout.mp_legend_view, parent, false);
        ViewHolder viewHolder = new ViewHolder(root);
        if (mMaxLines != -1) {
            viewHolder.tvName.setMaxLines(mMaxLines);
            viewHolder.tvName.setEllipsize(TextUtils.TruncateAt.END);
        }
        if (mHorizontalSpace != 0 || mVerticalSpace != 0) {
            root.setPadding(0, mVerticalSpace / 2, mHorizontalSpace, mVerticalSpace / 2);
        }

        return viewHolder;
    }

    /**
     * 绑定图例数据
     *
     * @param holder
     * @param position
     */
    protected void _onBindViewHolder(@NonNull ViewHolder holder, int position) {
        MPLegendEntry itemData = getItemData(position);
        if (itemData != null) {
            holder.iconView.setShape(itemData.getIconShape());
            holder.iconView.setColor(itemData.getIconColor());
            holder.iconView.setCircleColor(itemData.getCircleColor());
            holder.iconView.setCircleHoleColor(itemData.getCircleHoleColor());
            holder.iconView.postInvalidate();
            holder.tvName.setText(itemData.getLabel());
            if(mTextColor!=0){
                holder.tvName.setTextColor(mTextColor);
            }
            if(mTextSize!=0){
                holder.tvName.setTextSize(TypedValue.COMPLEX_UNIT_PX,mTextSize);
            }
            if(mIconSize!=0){
                ViewGroup.LayoutParams layoutParams = holder.iconView.getLayoutParams();
                if(layoutParams!=null){
                    layoutParams.width=mIconSize;
                    layoutParams.height=mIconSize;
                    holder.iconView.setLayoutParams(layoutParams);
                }
            }

            int labelColor = itemData.getLabelColor();
            if (labelColor != 0) {
                holder.tvName.setTextColor(labelColor);
            }
            IDataSet<?> dataSet = itemData.getDataSet();
            if (dataSet != null && !dataSet.isVisible()) {
                holder.tvName.setTextColor(mHideTextColor);
                holder.tvExtras.setTextColor(mHideTextColor);
            }

            if (mSupportHideDataSet) {
                holder.itemView.setClickable(true);
                holder.itemView.setTag(itemData);
                holder.itemView.setOnClickListener(onLegendClickListener);
            } else {
                holder.itemView.setClickable(false);
            }

        }

    }

    private OnClickListener onLegendClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            MPLegendEntry itemData = (MPLegendEntry) v.getTag();
            IDataSet<?> dataSet = itemData.getDataSet();
            if (dataSet != null && mChart != null) {
                dataSet.setVisible(!dataSet.isVisible());
                mChart.notifyDataSetChanged();
                mChart.postInvalidate();

            }
        }
    };

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public MPIconView iconView;
        public TextView tvName;
        public TextView tvExtras;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            iconView = itemView.findViewById(R.id.legendIconView);
            tvName = itemView.findViewById(R.id.legendTvName);
            tvExtras = itemView.findViewById(R.id.legendTvExtras);
        }
    }

    private class LegendAdapter extends RecyclerView.Adapter<ViewHolder> {
        @Override
        public int getItemCount() {
            return mData != null ? mData.size() : 0;
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return _onCreateViewHolder(parent);
        }


        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            _onBindViewHolder(holder, position);
        }


    }


}
